<template>
	<page-meta>
		<navigation-bar title="场景联动" title-align="center" background-color="#007AFF" />
	</page-meta>
	<view class="scene-wrap">
		<u-sticky zIndex="98" bgColor="#eef3f7">
			<view class="nav-bar">
				<view class="left-wrap">
					<view style="margin-right: 20rpx;">
						<u-icon name="list-dot" size="23" @click="isMenu = true"></u-icon>
					</view>
					<view v-if="!isSearch" style="margin-right: 20rpx;">
						<u-icon name="search" size="23" @click="isSearch = true"></u-icon>
					</view>
					<view v-else style="margin-right: 20rpx; width: 100%;">
						<!-- #ifndef APP-NVUE -->
						<u-input :customStyle="{ padding: '6rpx 18rpx'}" v-model="queryParams.sceneName"
							placeholder="请输入场景名称" shape="circle" @clear="handleClearSearch" clearable>
						<!-- #endif -->
							<!-- #ifdef APP-NVUE -->
							<u--input :customStyle="{ padding: '6rpx 18rpx'}" v-model="queryParams.sceneName"
								placeholder="请输入场景名称" shape="circle" @clear="handleClearSearch" clearable>
							<!-- #endif -->
								<template slot="prefix">
									<u-icon name="search" size="22" @click="isSearch = false"></u-icon>
								</template>
								<template slot="suffix">
									<u-button text="搜索" type="primary" shape="circle" size="mini"
										@click="handleSearch"></u-button>
								</template>
						<!-- #ifndef APP-NVUE -->
						</u-input>
						<!-- #endif -->
						<!-- #ifdef APP-NVUE -->
						</u--input>
						<!-- #endif -->
					</view>
				</view>
				<u-icon name="plus-circle-fill" size="23" color='#3c9cff' bold @tap="handleAddScene"></u-icon>
			</view>
			<view class="tab-wrap">
				<u-tabs :list="statusGroup" :scrollable="true" lineWidth="40" lineHeight="2" lineColor="transparent"
					:duration="100" :activeStyle="{ fontSize: '36rpx', color: '#3c9cff', fontWeight: 'bold' }"
					@change="handleStatusChange">
				</u-tabs>
			</view>
		</u-sticky>

		<view class="container-wrap">
			<view class="item-wrap" v-for="(item, index) in list" :key="index">
				<view class="card" :style="{ margin: index === 0 ? '0 30rpx 30rpx' : '30rpx'}"
					@click="handleSceneDetail(item.sceneId)">
					<view class="title">
						<u--text lines="1" :text="item.sceneName"></u--text>
						<u-icon name="arrow-right" color="#606266" customStyle="margin-right:5px;" size="14"></u-icon>
					</view>

					<view class="cond">条件：{{getCondName(item.cond)}}</view>
					<view class="cond">方式：{{getExecuteModeName(item.executeMode)}}</view>
					<view class="cond">任务：{{item.actionCount}}个</view>

					<view class="bottom-wrap" @tap.stop>
						<u--text lines="1" prefixIcon="/static/scene/once.png"
							iconStyle="width: 14px;height: 14px;margin-right: 3px;" size="13" text="执行一次"
							color='#3C9CFF' lineHeight="16" @click="handleRunOnce(item)"></u--text>
						<u-switch v-model="item.enable" @change="handleSwitchStatus(item)" :activeValue="1"
							:inactiveValue="2" activeColor="#3C9CFF" inactiveColor="#dbdbdb" size="18"></u-switch>
					</view>
				</view>
			</view>
			<u-loadmore :status="loadmoreStatus" v-if="total > queryParams.pageSize" loading-text="努力加载中..."
				loadmoreText="轻轻上拉" nomoreText="实在没有了" marginTop="20" />
		</view>
		<view class="other">
			<u-empty mode="data" :show="total === 0" icon="/static/common/empty.png" marginTop="60"
				text="数据为空"></u-empty>

			<u-popup :show="isMenu" mode="top" :closeOnClickOverlay="true" :round="5" @close="isMenu = false">
				<view class="menu-popup-wrap">
					<view class="group-wrap">
						<u-cell-group :border="false">
							<view class="cell-wrap">
								<u-cell icon="grid" title="管理" :border="false" isLink @click="goToSceneList"></u-cell>
							</view>
							<view class="cell-wrap">
								<u-cell icon="file-text" title="告警" :border="false" isLink
									@click="goToAlertList"></u-cell>
							</view>
						</u-cell-group>
					</view>
				</view>
			</u-popup>
		</view>
	</view>
</template>

<script>
	import { listScene, runScene, updateStatus } from '@/apis/modules/scene';

	export default {
		data () {
			return {
				isMenu: false,
				isSearch: true,
				// 状态列表
				statusGroup: [{
						id: null,
						name: '全部'
					},
					{
						id: 1,
						name: '启用'
					},
					{
						id: 2,
						name: '未启用'
					}
				],
				queryParams: {
					pageNum: 1,
					pageSize: 4,
					enable: null,
					sceneName: '',
				},
				list: [],
				total: 0,
				loadmoreStatus: 'loadmore', // 刷新和加载相关
			};
		},
		onLoad () {
			this.getList();
		},
		methods: {
			// 场景状态改变事件
			handleStatusChange (item) {
				this.list = [];
				this.queryParams.enable = item.id;
				this.queryParams.pageNum = 1;
				this.getList();
			},
			// 场景列表
			goToSceneList () {
				uni.navigateTo({
					url: '/pagesA/scene/list'
				});
				this.isMenu = false;
			},
			// 告警记录
			goToAlertList () {
				uni.navigateTo({
					url: '/pagesA/scene/alert/index'
				});
				this.isMenu = false;
			},
			// 新增场景
			handleAddScene () {
				// 使用vuex会导致小程序性能问题所以存储本地
				let sceneData = {
					sceneId: null,
					sceneName: '',
					remark: '',
					enable: 1, // 状态，1：启动，2：暂停
					cond: 1, // 触发条件，1：任意条件，2：所有条件，3：不满足
					silentPeriod: 0, // 静默时间
					executeMode: 1, // 执行方式，1：串行，2：并行
					executeDelay: 0, // 延时执行
					hasAlert: 2, // 1：包含告警，2：不包含告警
					applicationName: 'fastbee', // 固定值
					triggers: [],
					actions: [],
				};
				const storage = uni.getStorageSync('sceneData');
				if (storage) {
					uni.removeStorageSync('sceneData');
				}
				uni.setStorageSync('sceneData', sceneData);
				uni.removeStorageSync('callback');
				uni.navigateTo({ url: '/pagesA/scene/detail' });
			},
			// 场景详情
			handleSceneDetail (id) {
				const storage = uni.getStorageSync('sceneData');
				if (storage) {
					uni.removeStorageSync('sceneData');
				}
				const sceneData = {
					sceneId: null,
					sceneName: '',
					remark: '',
					enable: 1, // 状态，1：启动，2：暂停
					cond: 1, // 触发条件，1：任意条件，2：所有条件，3：不满足
					silentPeriod: 0, // 静默时间
					executeMode: 1, // 执行方式，1：串行，2：并行
					executeDelay: 0, // 延时执行
					hasAlert: 2, // 1：包含告警，2：不包含告警
					applicationName: 'fastbee', // 固定值
					triggers: [],
					actions: [],
				};
				uni.setStorageSync('sceneData', sceneData);
				uni.removeStorageSync('callback');
				uni.navigateTo({ url: '/pagesA/scene/detail?sceneId=' + id });
			},
			// 获取条件
			getCondName (cond) {
				if (cond === 1) {
					return '任意条件'
				} else if (cond === 2) {
					return '所有条件'
				} else if (cond === 3) {
					return '不满足条件'
				} else {
					return '未知'
				}
			},
			getExecuteModeName (mode) {
				if (mode === 1) {
					return '串行'
				} else if (mode === 2) {
					return '并行'
				} else {
					return '未知'
				}
			},
			// 获取场景列表
			getList () {
				listScene(this.queryParams)
					.then(res => {
						const { rows, total } = res;
						this.list = this.list.concat(rows);
						this.total = total;
						console.log(rows, '场景联动列表');
					})
					.catch(err => {
						console.log(err);
					});
			},
			// 搜索
			handleSearch () {
				this.list = [];
				this.queryParams.pageNum = 1;
				this.getList();
			},
			handleClearSearch () {
				this.handleSearch();
			},
			// 下拉刷新
			onPullDownRefresh () {
				console.log('下拉刷新');
				this.list = [];
				this.total = 0;
				this.queryParams.pageNum = 1;
				// 模拟网络请求
				setTimeout(x => {
					this.getList();
					uni.stopPullDownRefresh();
				}, 1000);
			},
			// 上拉加载
			onReachBottom () {
				console.log('上拉加载');
				this.loadmoreStatus = 'loading';
				this.queryParams.pageNum = ++this.queryParams.pageNum;
				// 模拟网络请求
				setTimeout(() => {
					if ((this.queryParams.pageNum - 1) * this.queryParams.pageSize >= this.total) {
						this.loadmoreStatus = 'nomore';
					} else {
						this.loadmoreStatus = 'loading';
						this.getList();
					}
				}, 1000);
			},
			//执行一次
			handleRunOnce (data) {
				const params = { sceneId: data.sceneId };
				runScene(params).then((res) => {
					uni.showToast({
						icon: 'none',
						title: res.msg
					});
				});
			},
			// 切换状态
			handleSwitchStatus (data) {
				const params = {
					sceneId: data.sceneId,
					enable: data.enable,
				}
				updateStatus(params).then((res) => {
					if (res.code === 200) {
						uni.showToast({
							icon: 'none',
							title: '切换成功'
						});
					} else {
						uni.showToast({
							icon: 'none',
							title: '切换失败'
						});
					}
				});
			},
		}
	};
</script>

<style>
	page {
		height: 100%;
		background: #eef3f7;
	}
</style>
<style lang="scss" scoped>
	.scene-wrap {
		height: 100%;

		.nav-bar {
			display: flex;
			flex-direction: row;
			justify-content: space-between;
			align-items: center;
			margin: 24rpx 26rpx 0;
			height: 74rpx;

			.left-wrap {
				flex: 1;
				display: flex;
				flex-direction: row;
				align-items: center;
			}
		}

		.tab-wrap {
			padding: 0 12rpx 10rpx 12rpx;

			.add-btn {
				padding: 0 20rpx;
			}
		}

		.container-wrap {
			padding-bottom: 120rpx;

			.item-wrap {
				.card {
					box-shadow: 0 2rpx 0rpx 0 rgba(0, 0, 0, 0.1);
					border-radius: 20rpx;
					padding: 30rpx;
					background-color: #fff;

					.title {
						padding: 10rpx 0;
						display: flex;
						flex-direction: row;
					}

					.cond {
						font-size: 12px;
						color: #7e7e7e;
						margin-top: 10rpx;
					}

					.bottom-wrap {
						display: flex;
						flex-direction: row;
						padding: 20rpx 0 10rpx;
					}
				}
			}
		}

		.other {
			.menu-popup-wrap {
				.group-wrap {
					background-color: #fff;
					border-radius: 10rpx;

					.cell-wrap {
						padding: 6rpx 0;

						&:not(:last-child) {
							border-bottom: 1rpx solid #F1F2F5;
						}
					}
				}
			}

			// 小程序中popup坑
			::v-deep(.u-safe-bottom)  {
				display: none;
			}
		}
	}
</style>